package com.campus.runrun.common.exception;


import com.campus.runrun.common.utils.ExceptionUtils;
import com.campus.runrun.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author BichonCode
 * @email chenzhichaohh@163.com
 * @date 2020-07-31 00:55:44
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.campus.runrun.controller")
public class ExceptionControllerAdvice {

    /**
     * 不能精确匹配的异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public R headleValidException(Throwable throwable) {
        log.error("未知错误:", throwable);
        return R.error();
    }

    /**
     * 不能精确匹配的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R headleValidException(Exception exception) {
        log.error("未知错误:", exception.getMessage());
        return R.error();
    }


    /**
     * 方法参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R headleValidException(MethodArgumentNotValidException e) {
        log.error("异常类型为：{}", e.getClass());
        log.error("异常信息为：{}", ExceptionUtils.getMessage(e));
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((errorError) -> {
            errorMap.put(errorError.getField(), errorError.getDefaultMessage());
        });
        return R.error(ResultCodeEnum.PARAM_ERROR).put("data", errorMap);
    }


    /**
     * 普通异常(一般为手动抛出，用户操作不当服务端抛出的异常)
     * @param customException
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R headleValidException(CustomException customException) {
        ResultCodeEnum resultCodeEnum = customException.getResultCodeEnum();
        log.warn("Custom异常信息为{}", ExceptionUtils.getMessage(customException));
        log.warn("响应状态码code:{}, 响应信息msg：{}", resultCodeEnum.getCode(),resultCodeEnum.getSuccess());
        return R.error(resultCodeEnum);
    }

    /**
     * 普通异常(一般为手动抛出，用户操作不当服务端抛出的异常)
     * @param unauthorizedException
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public R headleValidException(UnauthorizedException unauthorizedException) {
        log.warn("无权访问，异常信息为{}", ExceptionUtils.getMessage(unauthorizedException));
        return R.error(ResultCodeEnum.UNAUTHORIZED_ERROR);
    }






}
